package com.strato.mvc.api.v1_0_0.util;

import javax.servlet.http.HttpServletRequest;

public class RequestParser {

	public static RequestMeta parse(HttpServletRequest request){
		String url=request.getRequestURL().toString();
		String context=request.getContextPath();
		RequestMeta meta=parse(url,context);
		return meta;
	}

	private static RequestMeta parse(String url, String context) {
		String protocol=null;
		String domainPort=null;
		String domain=null;
		String path=null;
		int port=80;
		{
			String t="://";
			int index = url.indexOf(t);
			protocol = url.substring(0, index);
			url=url.substring(index+t.length());
		}
		{
			String t="/";
			int index = url.indexOf(t);
			domainPort=url.substring(0,index);
			url=url.substring(index);
		}
		{
			int index=domainPort.indexOf(":");
			if(index==-1){
				if("https".equalsIgnoreCase(protocol)){
					port=443;
				}else if("http".equalsIgnoreCase(protocol)){
					port=80;
				}
				domain=domainPort;
			}else{
				port=Integer.valueOf(domainPort.substring(index+":".length()));
				domain=domainPort.substring(0,index);
			}
		}
		{
			path=url.substring(context.length());
			if(path.startsWith("/")){
				path=path.substring(1);
			}
		}
		RequestMeta meta=new RequestMeta();
		meta.setContext(context);
		meta.setDomain(domain.toLowerCase());
		meta.setPath(path);
		meta.setPort(port);
		meta.setProtocol(protocol);
		return meta;
	}
}